package com.douwong.student.synscreen;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.Config;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.ScreenUtils;
import com.douwong.student.utils.TimeUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;

import static com.lidroid.xutils.bitmap.core.BitmapDecoder.calculateInSampleSize;


public class SynScreenActivity extends ClassBaseActivity implements SynUdpService.ScreenDataNotify {
	private ImageView mIvScreen=null;
	private TextView remind_tv=null;
	private SynUdpService mUdpService=null;	
	private Bitmap mBitmap=null;
	private BitmapDrawable mDrawable=null;	
	public static final String TAG="ScreenActivity";
	private boolean PAGECHANGE=false;

public static void startActivity(Context context){
	Intent intent=new Intent(context,SynScreenActivity.class);
	context.startActivity(intent);

}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
					case CommonConfig.SYNSCREEN_CLOSE:
					case Config.LOGIN_CLASS_FAILURE:
					case Config.TEACHER_LEAVE_CLASS:
					finish();
					break;
					case Intent.ACTION_SCREEN_OFF:
						closeUdpWork();
						break;
			}

		}
	};

	private  Handler uiRefresh=new Handler(){

		@Override
		public void handleMessage(Message msg) {		
			super.handleMessage(msg);
			
			switch (msg.what) {
			case 1:
				Bundle bundle=msg.getData();
				byte[] bytes=bundle.getByteArray("sd");
				
				try{			
					if (mBitmap != null) {
						mBitmap.recycle();
						mBitmap = null;
					}
					if (mDrawable != null) {
						mDrawable = null;
					}
					System.gc();
					LogUtils.i(TAG,"转化bitmap 开始 ： "+ TimeUtils.getTime());
				//	mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
					mBitmap=	byteToBitmap(bytes);
					LogUtils.i(TAG,"转化bitmap 结束 ： "+ TimeUtils.getTime());
					if (mBitmap != null) {
						mIvScreen.setImageBitmap(mBitmap);
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case 2:
				remind_tv.setVisibility(View.GONE);
				mIvScreen.setVisibility(View.VISIBLE);
				break;
			}
		}	

	};

	/**
	 * 数组转化bitmap
	 * @param imgByte
	 * @return
	 */
	private   Bitmap byteToBitmap(byte[] imgByte) {
		InputStream input = null;
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize=calculateInSampleSize(options, ScreenUtils.getScreenWidth(),ScreenUtils.getScreenHeight());
		input = new ByteArrayInputStream(imgByte);
		SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
				input, null, options));
		bitmap = (Bitmap) softRef.get();
		if (imgByte != null) {
			imgByte = null;
		}

		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

	@Override
	protected void initView() {

		setContentView(R.layout.act_synscreen);

		mIvScreen = (ImageView)findViewById(R.id.view);
		remind_tv=(TextView)findViewById(R.id.load_remind_tv);
	}

	@Override
	protected void initData() {
		super.initData();

		try{
			//打开WIFI组播
			WifiManager wifi = (WifiManager)getApplicationContext(). getSystemService(Context.WIFI_SERVICE);
			MulticastLock lock = wifi.createMulticastLock("mylock");
			lock.acquire();
			//添加广播
			IntentFilter filter = new IntentFilter();
			filter.addAction(CommonConfig.SYNSCREEN_CLOSE);
			filter.addAction(Config.LOGIN_CLASS_FAILURE);
			filter.addAction(Config.TEACHER_LEAVE_CLASS);
			//屏保：系统发出的广播
			filter.addAction(Intent.ACTION_SCREEN_OFF);
			this.registerReceiver(mReceiver, filter);

		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	  long firClick;
      long secClick;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
          firClick = secClick;
          secClick = System.currentTimeMillis();
          if (secClick - firClick < 1000) {
        	  if(!BaseApplication.isLoginClass || !BaseApplication.isTeaching){
        		 finish(); 
        	  }
          }
  }
		return super.onTouchEvent(event);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if (mUdpService != null) {
			mUdpService.stop();
			mUdpService = null;
		}
		if (mReceiver!=null){
			unregisterReceiver(mReceiver);
			mReceiver=null;
		}

		if (mBitmap != null &&!mBitmap.isRecycled()) {
			mBitmap.recycle();
			mBitmap = null;
		}

	}


	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
		LogUtils.i(TAG,"onResume  开始 :"+ TimeUtils.getTime());
		
		if(mUdpService==null){
			mUdpService=new SynUdpService();
			mUdpService.setScreenDataChangeListener(this);
			mUdpService.start();
		}else {
			Log.i(TAG, "mUdpService not null");
		}
		
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.d(TAG, "onStop");
	}



	@Override
	public void DataChangeNotify(byte[] bytes) {		
		if(!PAGECHANGE){
			PAGECHANGE=true;
			uiRefresh.sendEmptyMessage(2);			
		}
		Bundle bundle=new Bundle();
		bundle.putByteArray("sd", bytes);	
		Message message=uiRefresh.obtainMessage();
		message.what=1;
		message.setData(bundle);
		uiRefresh.sendMessage(message);			
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
			if(BaseApplication.isLoginClass){
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	private void closeUdpWork(){
		
		if (mUdpService != null) {
			mUdpService.stop();
			mUdpService = null;
		}
		
//		finish();
	}

}
